package com.example.mediamoudle.thumb

import android.content.Intent
import android.os.Handler
import android.util.Log
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.android.baselibrary.base.BaseActivity
import com.example.mediamoudle.R
import com.example.mediamoudle.databinding.ActivityThumbBinding
import com.example.mediamoudle.pickvideo.PickVideoActivity
import com.example.mediamoudle.pickvideo.VideoFile
import com.example.mediamoudle.router.MediaRouterPath
import com.example.mediamoudle.utlis.MediaUtils
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.analytics.AnalyticsListener
import com.google.android.exoplayer2.source.ConcatenatingMediaSource
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.upstream.DefaultDataSource
import com.google.android.exoplayer2.video.VideoSize
import java.util.*
import kotlin.concurrent.thread

/**
 * 视频轴缩放
 */

@Route(path = MediaRouterPath.MEDIA_THUMB_VIDEO)
class ThumbActivity : BaseActivity<ActivityThumbBinding>(), View.OnClickListener {
    val VIDEO_URL = "/storage/emulated/0/70651.mp4"
    private val videos = mutableListOf<VideoClip>()

    private lateinit var mPlayer: ExoPlayer
    override fun getLayoutId(): Int = R.layout.activity_thumb

    var mFirstDuration = 0L

    private var mIndex = 0
    val MIN_BUFFER_MS = 5_000 // 最小缓冲时间，
    val MAX_BUFFER_MS = 7_000 // 最大缓冲时间
    val PLAYBACK_BUFFER_MS = 500 // 最小播放缓冲时间，只有缓冲到达这个时间后才是可播放状态
    val REBUFFER_MS = 1_000 // 当缓冲用完，再次缓冲的时间
    override fun initView() {
        val halfScreenWidth = getScreenWidth() / 2
        Log.i("adfs", "initView: $halfScreenWidth")
        mBinding.rvFrame.setPadding(halfScreenWidth, 0, halfScreenWidth, 0)



        bindVideoData()

        val loadControl = DefaultLoadControl.Builder()
            .setPrioritizeTimeOverSizeThresholds(true)//缓冲时时间优先级高于大小
            .setBufferDurationsMs(MIN_BUFFER_MS, MAX_BUFFER_MS, PLAYBACK_BUFFER_MS, REBUFFER_MS)
            .build()

        //创建播放器
        mPlayer = ExoPlayer.Builder(this).
            setLoadControl(loadControl).
        build()
        //设置显示界面
        mPlayer.setVideoSurfaceView(mBinding.surfaceView)
        mPlayer.repeatMode = Player.REPEAT_MODE_ALL

        //DefaultAnalyticsCollector(this)
        //mBinding.exoController.player = mPlayer


        mBinding.zoomFrameLayout.onSeekVideoProgressChangeListener =
            object : ZoomFrameLayout.OnSeekVideoProgressChangeListener {
                override fun onPause() {
                    mPlayer.pause()
                }

                override fun upDateVideoProgress(time: Long) {
                    Log.i("TAG12", "upDateVideoProgress:开始seekTo time:$time")

                    mPlayer.pause()

                        mPlayer.seekTo(index,findIndexByTime(time))


                }

            }
        mBinding.floating.setOnClickListener(this)
        mBinding.btn.setOnClickListener {
            if (mPlayer.isPlaying){
                mBinding.btn.setText("播放")
                mPlayer.pause()
            }else{
                mPlayer.play()
                mBinding.btn.setText("暂停")
            }
        }


    }
    var mTargetRealSeekPos = 0L
    var mTargetPlayStatue = ""
    val SEEKED = "seeking"
    public fun realSeekTo(msec:Long ) {
        if (mPlayer != null) {
           //如果上次滑动的还没结束,那么保存状态,等seekto结束再拉动
            if (mTargetPlayStatue == SEEKED) {
                mTargetRealSeekPos = msec;
            } else {
                mPlayer.seekTo(msec.toLong());
                mTargetPlayStatue = SEEKED;
            }
        }
    }

    private fun setVideo(path: ArrayList<VideoFile>) {
        videos.clear()
        val defaultMediaSourceFactory = DefaultDataSource.Factory(this)

       var list :Array<MediaSource> = arrayOf()
        path.forEachIndexed {index, video->
            Log.i("TAG123", "setVideo: ${video.path}")
            val duration = MediaUtils.getVideoDuration(this, video.path)
            videos.add(
                VideoClip(
                    UUID.randomUUID().toString(), video.path,
                    duration, 0, duration
                )
            )
            //添加视频
            //list.add(MediaSource.Factory)
         //   list[index] = ProgressiveMediaSource.Factory(defaultMediaSourceFactory).createMediaSource(MediaItem.fromUri(video.path))

        }
  /*     val mediaSource =   ConcatenatingMediaSource(true,ProgressiveMediaSource.Factory(defaultMediaSourceFactory).
       createMediaSource(MediaItem.fromUri(path[0].path)),ProgressiveMediaSource.Factory(defaultMediaSourceFactory).
       createMediaSource(MediaItem.fromUri(path[1].path)))*/
        path.forEach {
            mPlayer.addMediaItem(MediaItem.fromUri(it.path))
        }
     //   mPlayer.setMediaSource(mediaSource)

        mPlayer.prepare()

        mPlayer.play()
        handler.post(runnable)



        //更新轨道信息
        updateVideos()


    }


    /* private val mShowProgress: Runnable = object : Runnable {
         override fun run() {

            val position =  mBinding.videoView.currentPosition
            if ( mBinding.videoView.isPlaying){
                Log.i("TAGthumb", "run:$position ")
                mBinding.zoomFrameLayout.updateTimeByScroll(position.toLong(),true)
            }

             mBinding.videoView.postDelayed(this, 30)
         }
     }*/

    private fun updateVideos() {
        mBinding.rvFrame.rebindFrameInfo()
        updateTimeLineValue(false)
    }

    private fun bindVideoData() {
        mBinding.zoomFrameLayout.scaleEnable = true
        mBinding.rvFrame.videoData = videos

        mBinding.zoomFrameLayout.timeLineValue = timeLineValue
        mBinding.zoomFrameLayout.dispatchTimeLineValue()
        mBinding.zoomFrameLayout.dispatchScaleChange()
    }

    // 创建一个Handler用于定时更新SeekBar
    var handler: Handler = Handler()
    var runnable = Runnable {

         upDateTime()
         }

    fun  upDateTime(){
        Log.i("TAGRunnable", "initListener mFirstDuration: ${mPlayer.currentPosition}")
        handler.postDelayed(runnable, 200); // 每秒更新一次
    }
   var index = 0
    override fun initListener() {
        var currentDuration = 0L
        mPlayer.setVideoFrameMetadataListener { presentationTimeUs, releaseTimeNs, format, mediaFormat ->


           runOnUiThread {

               mIndex =  mPlayer.currentWindowIndex
                mBinding.zoomFrameLayout.updateTimeByScroll(mPlayer.currentPosition+getLastTime(mIndex), true)
            }
            // }
        }


        mPlayer.addListener(object : Player.Listener {
            override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
                super.onMediaItemTransition(mediaItem, reason)
            }
            override fun onPlaybackStateChanged(playbackState: Int) {
                super.onPlaybackStateChanged(playbackState)


                when(playbackState){
                    Player.STATE_READY ->{
                        Log.i("onPlaybackStateChanged", "STATE_READY "+mPlayer.currentWindowIndex)
                        if (mTargetPlayStatue == SEEKED){

                        }
                    }
                }
            }

            override fun onPositionDiscontinuity(
                oldPosition: Player.PositionInfo,
                newPosition: Player.PositionInfo,
                reason: Int
            ) {
                super.onPositionDiscontinuity(oldPosition, newPosition, reason)
            }
        })

     mPlayer.addAnalyticsListener(object :AnalyticsListener{
         override fun onRenderedFirstFrame(eventTime: AnalyticsListener.EventTime, output: Any, renderTimeMs: Long) {
             super.onRenderedFirstFrame(eventTime, output, renderTimeMs)
             Log.i("TAG", "onRenderedFirstFrame: 111")
         }

         override fun onVideoSizeChanged(eventTime: AnalyticsListener.EventTime, videoSize: VideoSize) {
             super.onVideoSizeChanged(eventTime, videoSize)
             Log.i("TAG", "onRenderedFirstFrame: onVideoSizeChanged")
         }
     })



    }

    private fun getLastTime(index:Int):Long{
        var time = 0L
        for (i in 0 until  index){
            time += videos[i].durationMs
        }
        return time;
    }

    private fun findIndexByTime(time:Long):Long{
        var t = 0L
        for (i in 0 until  videos.size){
          if (videos[i].durationMs+t >time){
              index = i;
              break
          }
           t += videos[i].durationMs
        }
      return   time - t
    }


    val timeLineValue = TimeLineBaseValue()
    private val totalDurationMs: Long //当前正在播放视频的总时长
        get() {
            var result = 0L
            for (video in videos) {
                result += video.durationMs
            }
            return result
        }





    private fun  updateTimeLineValue(fromUser: Boolean = false) {
        timeLineValue.apply {
            val isFirst = duration == 0L
            duration = totalDurationMs
            if (time > duration) {
                time = duration
            }

            if (isFirst) {//首次
                resetStandPxInSecond()
            } else {
                fitScaleForScreen()
            }
            mBinding.zoomFrameLayout.dispatchTimeLineValue()
            mBinding.zoomFrameLayout.dispatchScaleChange()
        }
    }

    override fun onClick(v: View?) {
        startActivityForResult(Intent(this, PickVideoActivity::class.java), 1000)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 2000) {
            val path = data?.getParcelableArrayListExtra<VideoFile>("videoPath") as ArrayList<VideoFile>
            Log.i("TAG", "onActivityResult: path:${path.get(0).path}")
            if (path != null) {
                setVideo(path)
            }


        }
    }


    override fun onPause() {
        super.onPause()
        mPlayer.pause()
    }

    override fun onResume() {
        super.onResume()
        //mPlayer.play()
    }
}